import styles from './index.module.scss'
import ArticleItem from '../ArticleItem/index'
import { useEffect, useState } from 'react'
import { PullToRefresh, InfiniteScroll } from 'antd-mobile'
import { useDispatch, useSelector } from 'react-redux'
import { getArticleList } from '../../../../store/reducer/home'
import { sleep } from 'antd-mobile/es/utils/sleep'

const ArticleList = ({ channelId, activeId }) => {
  // console.log(activeId)
  const dispatch = useDispatch()
  const current = useSelector((state) => state.home.articleList[channelId])
  //是否有更多数据
  const [hasMore, setHasMore] = useState(true)
  //代表是否真正加载数据
  const [loading, setLoading] = useState(false)

  const loadMore = async () => {
    if (loading) return
    if (channelId !== activeId) return
    if (!current.timestamp) {
      setHasMore(false)
      return
    }
    setLoading(true)
    // console.log('加载' + channelId)
    try {
      await dispatch(getArticleList(channelId, current.timestamp, true))
      await sleep(2000)
    } finally {
      setLoading(false)
    }
  }
  useEffect(() => {
    if (current) return
    if (channelId === activeId) {
      dispatch(getArticleList(channelId, Date.now()))
    }
  }, [channelId, activeId, dispatch, current])

  if (!current) return null
  // console.log(current)
  return (
    <div className={styles.root}>
      <div className='articles'>
        <PullToRefresh
          onRefresh={async () => {
            setHasMore(true)
            await dispatch(getArticleList(channelId, Date.now()))
            // console.log('加载数据了')
          }}
        >
          {current.list.map((item) => (
            <div className='article-item' key={item.art_id}>
              <ArticleItem article={item}></ArticleItem>
            </div>
          ))}
        </PullToRefresh>
        {/* 下拉加载更多 */}
        <InfiniteScroll
          loadMore={loadMore}
          hasMore={hasMore}
          threshold={100}
        ></InfiniteScroll>
      </div>
    </div>
  )
}
export default ArticleList
